package com.lxq.LeetCode.combinationSum2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Solution {
    public static List<List<Integer>> res = new ArrayList<>();

    public static void main(String[] args) {
        int[] candidates = {2,5,2,1,2};
        System.out.println(combinationSum2(candidates, 5).toString());
    }

    public static List<List<Integer>> combinationSum2(int[] candidates, int target) {

        Arrays.sort(candidates);
        System.out.println(Arrays.toString(candidates));
        for (int i = 0; i < candidates.length - 1; i++) {
            LinkedList<Integer> tempList = new LinkedList<>();
            while (i > 0 && i < candidates.length - 1 && candidates[i] == candidates[i - 1]) {
                i++;
            }
            if (candidates[i] > target) {
                break;
            }
            if (candidates[i] == target) {
                List<Integer> list = new ArrayList<>();
                list.add(target);
                res.add(list);
                return res;
            } else {
                tempList.add(candidates[i]);
                backtrack(tempList, candidates, i + 1, target - candidates[i]);
            }
        }
        if (candidates[candidates.length - 1] == target) {
            List<Integer> list = new ArrayList<>();
            list.add(target);
            res.add(list);
        }
        return res;
    }

    public static void backtrack(LinkedList<Integer> tempList, int[] candidates, int start, int target) {
        for (int i = start; i < candidates.length; i++) {
            while (i > start && i < candidates.length-1 && candidates[i] == candidates[i - 1]) {
                i++;
            }
            if (candidates[i] > target) {
                break;
            }
            tempList.add(candidates[i]);
            if (candidates[i] == target) {
                List<Integer> list = (List<Integer>) tempList.clone();
                res.add(list);
                tempList.removeLast();
                break;
            } else {
                backtrack(tempList, candidates, i + 1, target - candidates[i]);
            }
            tempList.removeLast();
        }
    }
}
